package com.example.jasonrpc.registry.redis;

import com.example.jasonrpc.proto.Peer;
import com.example.jasonrpc.registry.RegistryCenter;
import com.example.jasonrpc.registry.RegistryDirectory;
import redis.clients.jedis.Jedis;

import java.util.*;
import java.util.stream.Collectors;

public class RedisRegistry implements RegistryCenter {
    private final Jedis jedis;

    public RedisRegistry(String centerIp, int centerPort) {
        jedis = new Jedis(centerIp, centerPort);
    }

    public static void main(String[] args) {
//        RedisRegistry redisRegistry = new RedisRegistry("127.0.0.1", 6379);
//        RegistryDirectory directory = new RegistryDirectory();
//        directory.setServiceClass("abc");
//        directory.setPeers(Collections.singletonList(new Peer("192.168.1.4", 9999)));
//        redisRegistry.unregister(directory);
    }

    private List<String> getDirectoryKeys(RegistryDirectory directory) {
        return directory.getPeers().stream()
                .map(peer -> "http://" + peer.getHost() + ":" + peer.getPort())
                .collect(Collectors.toList());
    }

    @Override
    public void register(RegistryDirectory directory) {
        Map<String, String> map = new HashMap<>();
        List<String> directoryKeys = getDirectoryKeys(directory);
        for (String directoryKey : directoryKeys) {
            map.put(directoryKey, "");
        }
        jedis.hset(directory.getServiceClass(), map);
    }

    @Override
    public void registerAll(List<RegistryDirectory> directories) {
        for (RegistryDirectory directory : directories) {
            register(directory);
        }
    }

    @Override
    public void unregister(RegistryDirectory directory) {
        List<String> directoryKeys = getDirectoryKeys(directory);
        jedis.hdel(directory.getServiceClass(), directoryKeys.toArray(new String[0]));
    }

    @Override
    public void unregisterAll(List<RegistryDirectory> directories) {
        for (RegistryDirectory directory : directories) {
            unregister(directory);
        }
    }
}
